namespace Vin.WebApi.Tests.Sse;

public static class SseExtension
{
    public static void UseSse(this WebApplication app, string url, UseSseOption option)
    {
        app.MapMethods(url, option.HttpMethods, async context =>
        {
            ISseService service = context.RequestServices.GetRequiredService<ISseService>();

            ISseClient client = new SseClient(context);

            service.AddClient(client);
            await client.OpenAsync(option.OpenAction);

            service.RemoveClient(client);

            if (option.EndAction != null) await option.EndAction(context, client);

            await client.CloseAsync();
        });
    }
}